package com.link.base.base.enterprise.controller;

import com.link.base.base.user.model.User;
import com.link.base.base.enterprise.model.Enterprise;
import com.link.base.base.enterprise.service.EnterpriseService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.CallParam;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.UserUtil;
import com.link.core.cllog.LCLogger;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author  unknwon
 * @date:   2018/11/12 9:46
 * @version 1.0
 */

@Controller
@RequestMapping("/link/enterprise")
public class EnterpriseController extends BasicController<Enterprise> {

    @Resource
    private EnterpriseService enterpriseService;

    @Override
    public BasicService<Enterprise> getBasicService() throws Exception {
        return enterpriseService;
    }

    @Override
    @RequestMapping(value = "/upsert")
    @ResponseBody
    public Map<String, Object> upsert(@RequestBody Enterprise entity, HttpSession session,
                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        /*MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> myfiles = multipartRequest.getFiles("myfile");*/
        try {
            beforUpsert(entity, request);
            checkData(entity, request);
            String base = "base";
            if (!getBasicService().isInsertFlag(entity) && !checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PUBLIC-002");
            }
            enterpriseService.upsert(entity);
            /*// 上传图片到服务器
            List<Image> list = enterpriseService.imgUpload(myfiles);
            // 将图片写到数据库
            enterpriseService.qrCodeImageUpate(entity, list);*/

            Enterprise newEntry = getBasicService().queryById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /***
     * 企业初始化
     */
    @RequestMapping(value = "/initializeCompany", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> initializeCompany(@JsonParam Enterprise entity,@JsonParam CallParam callParam,
                                                 HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            CoreUser user = UserUtil.getUser();
            String admin = "ADMIN000";
            if (!admin.equals(user.getUsername())) {
                result.put("success", false);
                result.put("result", "该帐号权限不足。");
                return result;
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", "未获取到当前登录用户。");
            return result;
        }
        try {
            enterpriseService.initEnterpriseInfo(entity, callParam);
            Enterprise enterprise = enterpriseService.queryById(entity);
            result.put("success", true);
            result.put("newRow", enterprise);
            result.put("message", "请使用" + entity.getUserName().toUpperCase() + "用户，手机号码后六位数字为密码进行登录");
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 删除企业
     */
    @RequestMapping(value = "/deleteCompany")
    @ResponseBody
    public Map<String, Object> deleteCompany(@JsonParam Enterprise entity,@JsonParam CallParam callParam, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            CoreUser user = UserUtil.getUser();
            Long zeros = 0L;
            Long oneToOne = 101L;
            if (zeros.equals(entity.getCode()) || oneToOne.equals(entity.getCode())
                    || "102".equals(entity.getCode()) || user.getCorpid().equals(entity.getCode())) {
                result.put("success", false);
                result.put("result", "安全性限制，您不能删除该条记录！");
                return result;
            }
            checkData(entity, request);
            String base = "base";
            if (!checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PUBLIC-031");
            }
            callParam.setParam1(entity.getId());
            callParam.setParam2(String.valueOf(entity.getCode()));
            enterpriseService.deleteCompany(callParam);
            String ok = "OK";
            if (ok.equals(callParam.getReturnStatus())) {
                result.put("success", true);

            } else {
                throw new Exception(callParam.getMsgData());
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 新建入驻信息的初始化操作
     */
    @RequestMapping(value = "/initNew")
    @ResponseBody
    public Map<String, Object> initNew(@JsonParam QueryParams qps, HttpSession session,
                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            // 以下密码策略：强安全认证
            Enterprise enterprise = new Enterprise();
            //标记
            enterprise.setRow_status("NEW");
            enterprise.setQdTaskFlag("Y");
            // 默认密码长度8
            enterprise.setPwMinLen(8);
            // 密码留存期3个月
            enterprise.setPwKeepDate(6);
            // 密码过期时间3个月
            enterprise.setPwExpireDate(3);
            // 密码强度：高
            enterprise.setPwGrade("high");
            //（修改密码时）手机号校验
            enterprise.setMobileVerifyFlag("Y");
            // 校验等级
            enterprise.setPwCheckGrade("refuse");
            enterprise.setForceHistyPw("Y");
            result.put("success", true);
            result.put("result", enterprise);
            return result;
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 刷新安全模式配置
     */
    @RequestMapping(value = "/refreshSecurityCorpIds")
    @ResponseBody
    public Map<String, Object> refreshCorpIds(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            enterpriseService.loadCorpidsWhichActiveStrictSecurityMode2Redis();
            result.put("success", true);
            return result;
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @Override
    public void beforUpsert(Enterprise entity, HttpServletRequest request) throws Exception {
        if ("".equals(entity.getDealerApplySelf())) {
            entity.setDealerApplySelf("N");
        }
        if ("".equals(entity.getCrmEnabled())) {
            entity.setCrmEnabled("N");
        }
        if ("".equals(entity.getDmsEnabled())) {
            entity.setDmsEnabled("N");
        }
        if ("".equals(entity.getAppEnabled())) {
            entity.setAppEnabled("N");
        }
    }

    /**
     * 更新企业认证图片
     *
     * @param enterprise
     */
    @RequestMapping("/updateVoucherImg")
    @ResponseBody
    public Map<String, Object> updateVoucherImg(@JsonParam Enterprise enterprise) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            enterpriseService.updateVoucherImg(enterprise);
            Enterprise newRow = enterpriseService.queryById(enterprise);
            result.put("success", true);
            result.put("newRow", newRow);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新企业对账单参数开启状态
     *
     * @param enterprise
     * @return
     */
    @RequestMapping(value = "/updateBillStateStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateBillStateStatus(@JsonParam Enterprise enterprise) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == enterprise.getId() || StringUtils.isEmpty(enterprise.getBillStatementFlag())) {
                throw new ServiceException("PUBLIC-024");
            }
            enterpriseService.updateBillStatementParam(enterprise);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping("/getEnterprisePwRule")
    @ResponseBody
    public Map<String, Object> getEnterprisePwRule(@JsonParam Enterprise enterprise,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            CoreUser user = UserUtil.getUser();
            enterprise.setCode(user.getCorpid());
            enterprise.setLoginCorpId(user.getCorpid());
            List<Enterprise> enterpriseList = enterpriseService.getEnterpriseByUserCode(enterprise);
            if (enterpriseList == null || enterpriseList.size() == 0) {
                throw new ServiceException("ENTER-002");
            } else if (enterpriseList.size() > 1) {
                throw new ServiceException("ENTER-003");
            }
            Enterprise entity = enterpriseList.get(0);
            enterprise.setAnonymousFlag("Y");
            enterprise.setPwMinLen(entity.getPwMinLen());
            enterprise.setPwCheckGrade(entity.getPwCheckGrade());
            enterprise.setPwGrade(entity.getPwGrade());
            enterprise.setPwKeepDate(entity.getPwKeepDate());
            enterprise.setForceHistyPw(entity.getForceHistyPw());
            result.put("success", true);
            result.put("result", entity);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 会员模块——根据corpid 查询企业
     *
     * @author yangxiaolin
     * @date 2018/3/28
     */
    @RequestMapping(value = "/queryByCode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryByCode(@RequestBody User user,
                                               HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Enterprise enterprise = enterpriseService.queryByCode(user.getCorpid());
            result.put("success", true);
            result.put("result", enterprise);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

}
